package exporter

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"excel-exporter/config"
	"excel-exporter/types"

	"github.com/xuri/excelize/v2"
)

// ExportAll 导出所有配置的Excel文件
func ExportAll(appConfig *types.Config) error {
	exports := config.GetAllExports(appConfig)
	
	for _, exportConfig := range exports {
		fmt.Printf("正在处理Excel文件: %s\n", exportConfig.ExcelPath)
		
		if err := ExportExcel(&exportConfig); err != nil {
			return fmt.Errorf("导出Excel文件 %s 失败: %w", exportConfig.ExcelPath, err)
		}
		
		fmt.Printf("Excel文件 %s 处理完成\n", exportConfig.ExcelPath)
	}
	
	return nil
}

// ExportExcel 导出单个Excel文件
func ExportExcel(exportConfig *types.ExportConfig) error {
	f, err := excelize.OpenFile(exportConfig.ExcelPath)
	if err != nil {
		return fmt.Errorf("打开Excel文件失败: %w", err)
	}
	defer f.Close()

	// 获取所有子表
	sheets := f.GetSheetList()

	for _, sheetName := range sheets {
		// 查找子表配置
		var sheetConfig *types.Sheet
		for _, s := range exportConfig.Sheets {
			if s.SheetName == sheetName {
				sheetConfig = &s
				break
			}
		}
		
		if sheetConfig == nil {
			fmt.Printf("跳过未配置的子表: %s\n", sheetName)
			continue
		}

		fmt.Printf("正在导出子表: %s\n", sheetName)
		
		result, err := exportSheet(f, sheetName, exportConfig, sheetConfig)
		if err != nil {
			return fmt.Errorf("导出子表 %s 失败: %w", sheetName, err)
		}

		if err := saveSheetFiles(exportConfig, sheetConfig, result); err != nil {
			return fmt.Errorf("保存子表 %s 文件失败: %w", sheetName, err)
		}
		
		fmt.Printf("子表 %s 导出成功\n", sheetName)
	}

	return nil
}

// exportSheet 导出一个子表
func exportSheet(f *excelize.File, sheetName string, exportConfig *types.ExportConfig, sheetConfig *types.Sheet) (*types.ExportResult, error) {
	rows, err := f.GetRows(sheetName)
	if err != nil {
		return nil, err
	}

	// 检查是否为常量表
	if sheetConfig.IsConstantTable {
		return exportConstantTable(rows, sheetConfig)
	}

	// 普通表的处理逻辑
	if len(rows) < 6 {
		return nil, fmt.Errorf("数据行数不足，至少需要6行")
	}

	// 解析字段信息
	fieldInfos := parseFieldInfos(rows[1:4])

	// 解析数据 - 传递sheetConfig参数
	serverData, clientData, duplicateKeys, emptyRows, err := parseData(rows[5:], fieldInfos, sheetConfig)
	if err != nil {
		return nil, err
	}

	// 输出警告信息
	if len(duplicateKeys) > 0 {
		fmt.Printf("Error: 子表 %s 主键重复(%s): %v\n", sheetName, getKeyField(sheetConfig), duplicateKeys)
		panic("error 不能存在重复的主键")
	}
	if len(emptyRows) > 0 {
		fmt.Printf("Info: 子表 %s 跳过 %d 个空行\n", sheetName, len(emptyRows))
	}

	// 应用自定义数据处理函数 - 服务端
	serverProcessor, err := config.GetProcessorForSheet(sheetConfig, "server")
	if err != nil {
		return nil, err
	}
	
	var serverExtra map[string]interface{}
	if serverProcessor != nil {
		serverData, serverExtra = serverProcessor(serverData, "server", sheetConfig)
	}

	// 应用自定义数据处理函数 - 客户端
	clientProcessor, err := config.GetProcessorForSheet(sheetConfig, "client")
	if err != nil {
		return nil, err
	}
	
	var clientExtra map[string]interface{}
	if clientProcessor != nil {
		clientData, clientExtra = clientProcessor(clientData, "client", sheetConfig)
	}

	// 生成导出内容
	return generateExportContent(serverData, clientData, sheetConfig, serverExtra, clientExtra, fieldInfos), nil
}

// getKeyField 获取键字段名称
func getKeyField(sheetConfig *types.Sheet) string {
	if sheetConfig.KeyField != "" {
		return sheetConfig.KeyField
	}
	return "Id" // 默认值
}

// exportConstantTable 导出常量表
func exportConstantTable(rows [][]string, sheetConfig *types.Sheet) (*types.ExportResult, error) {
	if len(rows) < 2 {
		return nil, fmt.Errorf("常量表数据行数不足")
	}

	// 解析常量表数据
	constantData, duplicateKeys, emptyRows, err := parseConstantData(rows, sheetConfig)
	if err != nil {
		return nil, err
	}

	// 输出警告信息
	if len(duplicateKeys) > 0 {
		fmt.Printf("Error: 常量表发现重复的键: %v\n", duplicateKeys)
		panic("Error 主键重复")
	}
	if len(emptyRows) > 0 {
		fmt.Printf("Info: 常量表跳过 %d 个空行\n", len(emptyRows))
	}

	// 应用自定义数据处理函数 - 服务端
	serverProcessor, err := config.GetProcessorForSheet(sheetConfig, "server")
	if err != nil {
		return nil, err
	}
	
	var serverExtra map[string]interface{}
	if serverProcessor != nil {
		// 常量表的处理器需要特殊处理
		_, serverExtra = serverProcessor([]types.DataRow{}, "server", sheetConfig)
	}

	// 应用自定义数据处理函数 - 客户端
	clientProcessor, err := config.GetProcessorForSheet(sheetConfig, "client")
	if err != nil {
		return nil, err
	}
	
	var clientExtra map[string]interface{}
	if clientProcessor != nil {
		// 常量表的处理器需要特殊处理
		_, clientExtra = clientProcessor([]types.DataRow{}, "client", sheetConfig)
	}

	// 生成导出内容
	return generateConstantExportContent(constantData, sheetConfig, serverExtra, clientExtra), nil
}

// parseConstantData 解析常量表数据
func parseConstantData(rows [][]string, sheetConfig *types.Sheet) (map[string]interface{}, []string, []int, error) {
	constantData := make(map[string]interface{})
	duplicateKeys := make([]string, 0)
	emptyRows := make([]int, 0)
	
	// 确定键字段和值字段
	keyField := "常量名"
	if sheetConfig.ConstantKeyField != "" {
		keyField = sheetConfig.ConstantKeyField
	}
	
	valueField := "常量值"
	if sheetConfig.ConstantValueField != "" {
		valueField = sheetConfig.ConstantValueField
	}

	// 查找键字段和值字段的索引
	keyFieldIndex := -1
	valueFieldIndex := -1
	typeFieldIndex := -1
	
	// 第一行是表头, 第二行是空行
	if len(rows) < 2 {
		return constantData, duplicateKeys, emptyRows, nil
	}
	
	headers := rows[0]
	for i, header := range headers {
		header = strings.TrimSpace(header)
		switch header {
		case keyField:
			keyFieldIndex = i
		case valueField:
			valueFieldIndex = i
		case "常量类型":
			typeFieldIndex = i
		}
	}
	
	if keyFieldIndex == -1 || valueFieldIndex == -1 {
		return constantData, duplicateKeys, emptyRows, fmt.Errorf("无法找到常量表的键字段或值字段")
	}
	
	// 从第二行开始是数据
	for rowIndex := 2; rowIndex < len(rows); rowIndex++ {
		row := rows[rowIndex]
		
		// 检查是否为空行
		if isEmptyRow(row) {
			emptyRows = append(emptyRows, rowIndex+1) // +1 是因为从第1行开始是表头
			continue
		}
		
		if len(row) <= keyFieldIndex || len(row) <= valueFieldIndex {
			continue
		}
		
		key := strings.TrimSpace(row[keyFieldIndex])
		valueStr := strings.TrimSpace(row[valueFieldIndex])
		
		if key == "" {
			continue
		}
		
		// 检查重复键
		if _, exists := constantData[key]; exists {
			duplicateKeys = append(duplicateKeys, key)
		}
		
		// 获取值的类型
		valueType := "string" // 默认类型
		if typeFieldIndex != -1 && len(row) > typeFieldIndex {
			valueType = strings.TrimSpace(row[typeFieldIndex])
		}
		
		// 转换值
		value := convertConstantValue(valueStr, valueType)
		constantData[key] = value
	}
	
	return constantData, duplicateKeys, emptyRows, nil
}

// convertConstantValue 转换常量表的值
func convertConstantValue(valueStr, valueType string) interface{} {
	if valueStr == "" {
		return getDefaultValue(valueType)
	}

	switch strings.ToLower(valueType) {
	case "int", "integer":
		if val, err := strconv.Atoi(valueStr); err == nil {
			return val
		}
		return valueStr
	case "float", "double", "number":
		if val, err := strconv.ParseFloat(valueStr, 64); err == nil {
			return val
		}
		return valueStr
	case "bool", "boolean":
		return parseBool(valueStr)
	case "array", "list":
		return parseArray(valueStr)
	case "map":
		return parseMap(valueStr)
	default:
		return valueStr
	}
}

// parseMap 解析map类型
func parseMap(valueStr string) map[string]interface{} {
	result := make(map[string]interface{})
	
	// 简单的map解析，格式如: key1:value1,key2:value2
	pairs := strings.Split(valueStr, ",")
	for _, pair := range pairs {
		kv := strings.SplitN(pair, ":", 2)
		if len(kv) == 2 {
			key := strings.TrimSpace(kv[0])
			value := strings.TrimSpace(kv[1])
			result[key] = value
		}
	}
	
	return result
}

// parseFieldInfos 解析字段信息
func parseFieldInfos(rows [][]string) []types.FieldInfo {
	if len(rows) < 3 {
		return nil
	}

	var fields []types.FieldInfo

	for i := 0; i < len(rows[0]) && i < len(rows[1]) && i < len(rows[2]); i++ {
		name := strings.TrimSpace(rows[1][i])
		if name == "" {
			continue
		}

		fields = append(fields, types.FieldInfo{
			Index:    i,
			Name:     name,
			Type:     strings.TrimSpace(rows[0][i]),
			ExportTo: strings.TrimSpace(rows[2][i]),
		})
	}

	return fields
}

// parseData 解析数据行，返回数据、重复键和空行信息
func parseData(rows [][]string, fieldInfos []types.FieldInfo, sheetConfig *types.Sheet) ([]types.DataRow, []types.DataRow, []string, []int, error) {
	serverData := make([]types.DataRow, 0)
	clientData := make([]types.DataRow, 0)
	
	// 用于检测重复Id
	keySet := make(map[string]bool)
	duplicateKeys := make([]string, 0)
	emptyRows := make([]int, 0)
	
	// 确定键字段，优先使用配置中的key_field，默认为"Id"
	keyField := "Id"
	if sheetConfig.KeyField != "" {
		keyField = sheetConfig.KeyField
	}
	
	// 查找键字段在fieldInfos中的索引
	keyFieldIndex := -1
	for _, field := range fieldInfos {
		if field.Name == keyField {
			keyFieldIndex = field.Index
			break
		}
	}
	
	// 如果找不到配置的键字段，使用默认的"Id"
	if keyFieldIndex == -1 {
		for _, field := range fieldInfos {
			if field.Name == "Id" {
				keyField = "Id"
				keyFieldIndex = field.Index
				break
			}
		}
	}

	for rowIndex, row := range rows {
		// 检查是否为空行
		if isEmptyRow(row) {
			emptyRows = append(emptyRows, rowIndex+6) // +6 是因为从第6行开始是数据行
			continue
		}

		serverRow := make(types.DataRow)
		clientRow := make(types.DataRow)

		// 提取键值用于重复检查
		var keyValue string
		if keyFieldIndex >= 0 && keyFieldIndex < len(row) {
			keyValue = strings.TrimSpace(row[keyFieldIndex])
			
			// 检查重复Id
			if keyValue != "" {
				if keySet[keyValue] {
					duplicateKeys = append(duplicateKeys, keyValue)
				} else {
					keySet[keyValue] = true
				}
			}
		}

		for _, field := range fieldInfos {
			if field.Index >= len(row) {
				continue
			}

			// 严格按照字段定义的类型转换值
			value := convertValueByFieldType(strings.TrimSpace(row[field.Index]), field)

			switch field.ExportTo {
			case "cs":
				serverRow[field.Name] = value
				clientRow[field.Name] = value
			case "s":
				serverRow[field.Name] = value
			case "c":
				clientRow[field.Name] = value
			default:
			}
		}

		if len(serverRow) > 0 {
			serverData = append(serverData, serverRow)
		}
		if len(clientRow) > 0 {
			clientData = append(clientData, clientRow)
		}
	}

	return serverData, clientData, duplicateKeys, emptyRows, nil
}

// isEmptyRow 检查是否为空行
func isEmptyRow(row []string) bool {
	if len(row) == 0 {
		return true
	}
	
	for _, cell := range row {
		if strings.TrimSpace(cell) != "" {
			return false
		}
	}
	
	return true
}

// convertValueByFieldType 根据字段定义的类型严格转换值
func convertValueByFieldType(valueStr string, field types.FieldInfo) interface{} {
	if valueStr == "" {
		return getDefaultValue(field.Type)
	}

	// 严格按照字段定义的类型转换，不进行自动类型推断
	switch strings.ToLower(field.Type) {
	case "int", "integer":
		if val, err := strconv.Atoi(valueStr); err == nil {
			return val
		}
		// 如果无法转换为整数，保持原字符串
		return valueStr
	case "float", "double", "number":
		if val, err := strconv.ParseFloat(valueStr, 64); err == nil {
			return val
		}
		// 如果无法转换为浮点数，保持原字符串
		return valueStr
	case "bool", "boolean":
		return parseBool(valueStr)
	case "array", "list":
		return parseArray(valueStr)
	case "string":
		// 字符串类型直接返回，不进行任何转换
		return valueStr
	default:
		// 默认当作字符串处理
		return valueStr
	}
}

// convertValue 根据类型转换值（兼容旧代码）
func convertValue(valueStr, valueType string) interface{} {
	if valueStr == "" {
		return getDefaultValue(valueType)
	}

	switch strings.ToLower(valueType) {
	case "int", "integer":
		if val, err := strconv.Atoi(valueStr); err == nil {
			return val
		}
		return 0
	case "float", "double", "number":
		if val, err := strconv.ParseFloat(valueStr, 64); err == nil {
			return val
		}
		return 0.0
	case "bool", "boolean":
		return parseBool(valueStr)
	case "array", "list":
		return parseArray(valueStr)
	default:
		return valueStr
	}
}

// parseBool 解析布尔值
func parseBool(valueStr string) bool {
	if val, err := strconv.ParseBool(valueStr); err == nil {
		return val
	}

	switch valueStr {
	case "是", "真", "对", "1":
		return true
	case "否", "假", "错", "0":
		return false
	default:
		return false
	}
}

// parseArray 解析数组
func parseArray(valueStr string) []interface{} {
	items := strings.Split(valueStr, ",")
	result := make([]interface{}, 0, len(items))
	
	for _, item := range items {
		trimmed := strings.TrimSpace(item)
		if trimmed != "" {
			// 尝试转换为数字
			if intVal, err := strconv.Atoi(trimmed); err == nil {
				result = append(result, intVal)
			} else if floatVal, err := strconv.ParseFloat(trimmed, 64); err == nil {
				result = append(result, floatVal)
			} else {
				result = append(result, trimmed)
			}
		}
	}
	
	return result
}

// getDefaultValue 获取类型的默认值
func getDefaultValue(valueType string) interface{} {
	switch strings.ToLower(valueType) {
	case "int", "integer", "float", "double", "number":
		return 0
	case "bool", "boolean":
		return false
	case "array", "list":
		return []interface{}{}
	default:
		return ""
	}
}

// generateExportContent 生成普通表的导出内容
func generateExportContent(serverData, clientData []types.DataRow, sheetConfig *types.Sheet, serverExtra, clientExtra map[string]interface{}, fieldInfos []types.FieldInfo) *types.ExportResult {
	result := &types.ExportResult{}

	// 获取键字段的类型信息
	keyFieldType := getKeyFieldType(sheetConfig, fieldInfos)

	// 生成JSON内容
	result.ServerJSON = generateJSONContent(serverData, sheetConfig, serverExtra)
	result.ClientJSON = generateJSONContent(clientData, sheetConfig, clientExtra)

	// 生成Lua内容
	result.ServerLua = generateLuaContent(serverData, sheetConfig, serverExtra, keyFieldType)
	result.ClientLua = generateLuaContent(clientData, sheetConfig, clientExtra, keyFieldType)

	return result
}

// generateConstantExportContent 生成常量表的导出内容
func generateConstantExportContent(constantData map[string]interface{}, sheetConfig *types.Sheet, serverExtra, clientExtra map[string]interface{}) *types.ExportResult {
	result := &types.ExportResult{}

	// 生成JSON内容
	result.ServerJSON = generateConstantJSONContent(constantData, sheetConfig, serverExtra)
	result.ClientJSON = generateConstantJSONContent(constantData, sheetConfig, clientExtra)

	// 生成Lua内容
	result.ServerLua = generateConstantLuaContent(constantData, sheetConfig, serverExtra)
	result.ClientLua = generateConstantLuaContent(constantData, sheetConfig, clientExtra)

	return result
}

// getKeyFieldType 获取键字段的类型
func getKeyFieldType(sheetConfig *types.Sheet, fieldInfos []types.FieldInfo) string {
	keyField := "Id"
	if sheetConfig.KeyField != "" {
		keyField = sheetConfig.KeyField
	}

	// 查找键字段的类型定义
	for _, field := range fieldInfos {
		if field.Name == keyField {
			return strings.ToLower(field.Type)
		}
	}
	
	return "string" // 默认类型
}

// generateJSONContent 生成普通表的JSON内容
func generateJSONContent(data []types.DataRow, sheetConfig *types.Sheet, extra map[string]interface{}) string {
	// 转换数据为以key为索引的map
	dataMap := convertDataToMap(data, sheetConfig)
	
	// 创建顶层数据结构
	jsonData := types.JSONData{
		Data:  dataMap,
		Extra: extra,
	}
	
	// 转换为JSON
	jsonBytes, err := json.MarshalIndent(jsonData, "", "  ")
	if err != nil {
		// 如果出错，返回空的JSON
		return `{"data": {}}`
	}
	
	return string(jsonBytes)
}

// generateConstantJSONContent 生成常量表的JSON内容
func generateConstantJSONContent(constantData map[string]interface{}, sheetConfig *types.Sheet, extra map[string]interface{}) string {
	// 创建顶层数据结构
	constantJSONData := types.ConstantData{
		Data:  constantData,
		Extra: extra,
	}
	
	// 转换为JSON
	jsonBytes, err := json.MarshalIndent(constantJSONData, "", "  ")
	if err != nil {
		// 如果出错，返回空的JSON
		return `{"data": {}}`
	}
	
	return string(jsonBytes)
}

// generateLuaContent 生成普通表的Lua内容
func generateLuaContent(data []types.DataRow, sheetConfig *types.Sheet, extra map[string]interface{}, keyFieldType string) string {
	// 转换数据为以key为索引的map，严格按照类型处理
	dataMap := convertDataToMapWithStrictType(data, sheetConfig, keyFieldType)
	
	var builder strings.Builder
	
	builder.WriteString("return {\n")
	
	// 添加data字段
	builder.WriteString("    data = {\n")
	
	if len(dataMap) > 0 {
		// 收集键并排序
		keys := make([]string, 0, len(dataMap))
		for k := range dataMap {
			keys = append(keys, k)
		}
		
		for i, key := range keys {
			row := dataMap[key]
			// 根据键字段类型严格格式化Lua键
			builder.WriteString(fmt.Sprintf("        %s = {", formatLuaKeyStrict(key, keyFieldType)))
			
			first := true
			// 保持字段顺序一致
			fieldOrder := getFieldOrder(row)
			for _, fieldKey := range fieldOrder {
				if !first {
					builder.WriteString(", ")
				}
				builder.WriteString(formatLuaValue(fieldKey, row[fieldKey]))
				first = false
			}
			
			if i < len(keys)-1 {
				builder.WriteString("},\n")
			} else {
				builder.WriteString("}\n")
			}
		}
	}
	
	builder.WriteString("    }")
	
	// 添加额外字段
	if extra != nil && len(extra) > 0 {
		builder.WriteString(",\n")
		builder.WriteString("    extra = {\n")
		
		first := true
		for key, value := range extra {
			if !first {
				builder.WriteString(",\n")
			}
			builder.WriteString(fmt.Sprintf("        %s = ", key))
			builder.WriteString(formatLuaValueSimple(value))
			first = false
		}
		
		builder.WriteString("\n    }")
	}
	
	builder.WriteString("\n}")
	
	return builder.String()
}

// generateConstantLuaContent 生成常量表的Lua内容
func generateConstantLuaContent(constantData map[string]interface{}, sheetConfig *types.Sheet, extra map[string]interface{}) string {
	var builder strings.Builder
	
	builder.WriteString("return {\n")
	
	// 添加data字段
	builder.WriteString("    data = {\n")
	
	if len(constantData) > 0 {
		// 收集键并排序
		keys := make([]string, 0, len(constantData))
		for k := range constantData {
			keys = append(keys, k)
		}
		
		for i, key := range keys {
			value := constantData[key]
			builder.WriteString(fmt.Sprintf("        %s = ", formatLuaKeyStrict(key, "string")))
			builder.WriteString(formatLuaValueSimple(value))
			
			if i < len(keys)-1 {
				builder.WriteString(",\n")
			} else {
				builder.WriteString("\n")
			}
		}
	}
	
	builder.WriteString("    }")
	
	// 添加额外字段
	if extra != nil && len(extra) > 0 {
		builder.WriteString(",\n")
		builder.WriteString("    extra = {\n")
		
		first := true
		for key, value := range extra {
			if !first {
				builder.WriteString(",\n")
			}
			builder.WriteString(fmt.Sprintf("        %s = ", key))
			builder.WriteString(formatLuaValueSimple(value))
			first = false
		}
		
		builder.WriteString("\n    }")
	}
	
	builder.WriteString("\n}")
	
	return builder.String()
}

// convertDataToMap 将数据转换为以key为索引的map（字符串键）
func convertDataToMap(data []types.DataRow, sheetConfig *types.Sheet) map[string]types.DataRow {
	dataMap := make(map[string]types.DataRow)
	
	if len(data) == 0 {
		return dataMap
	}

	// 确定键字段，默认为"Id"
	keyField := "Id"
	if sheetConfig.KeyField != "" {
		keyField = sheetConfig.KeyField
	}

	for _, row := range data {
		// 获取键值
		keyValue, exists := row[keyField]
		if !exists {
			// 如果指定的键字段不存在，跳过该行
			continue
		}
		
		// 将键值转换为字符串
		var keyStr string
		switch v := keyValue.(type) {
		case string:
			keyStr = v
		case int:
			keyStr = strconv.Itoa(v)
		case float64:
			keyStr = strconv.FormatFloat(v, 'f', -1, 64)
		default:
			keyStr = fmt.Sprintf("%v", v)
		}
		
		dataMap[keyStr] = row
	}
	
	return dataMap
}

// convertDataToMapWithStrictType 严格按照键字段类型转换数据
func convertDataToMapWithStrictType(data []types.DataRow, sheetConfig *types.Sheet, keyFieldType string) map[string]types.DataRow {
	dataMap := make(map[string]types.DataRow)
	
	if len(data) == 0 {
		return dataMap
	}

	// 确定键字段，默认为"Id"
	keyField := "Id"
	if sheetConfig.KeyField != "" {
		keyField = sheetConfig.KeyField
	}

	for _, row := range data {
		// 获取键值
		keyValue, exists := row[keyField]
		if !exists {
			// 如果指定的键字段不存在，跳过该行
			continue
		}
		
		// 根据键字段类型严格处理键值
		var keyStr string
		switch keyFieldType {
		case "int", "integer":
			// 对于数字类型，确保转换为数字字符串
			switch v := keyValue.(type) {
			case int:
				keyStr = strconv.Itoa(v)
			case float64:
				keyStr = strconv.FormatFloat(v, 'f', -1, 64)
			case string:
				// 如果值是字符串但类型应该是数字，尝试转换
				if intVal, err := strconv.Atoi(v); err == nil {
					keyStr = strconv.Itoa(intVal)
				} else {
					keyStr = v
				}
			default:
				keyStr = fmt.Sprintf("%v", keyValue)
			}
		case "string":
			// 对于字符串类型，确保所有值都作为字符串处理
			switch v := keyValue.(type) {
			case string:
				keyStr = v
			case int, float64, bool:
				keyStr = fmt.Sprintf("%v", v)
			default:
				keyStr = fmt.Sprintf("%v", keyValue)
			}
		default:
			// 其他类型按原样处理
			switch v := keyValue.(type) {
			case string:
				keyStr = v
			case int:
				keyStr = strconv.Itoa(v)
			case float64:
				keyStr = strconv.FormatFloat(v, 'f', -1, 64)
			default:
				keyStr = fmt.Sprintf("%v", v)
			}
		}
		
		dataMap[keyStr] = row
	}
	
	return dataMap
}

// formatLuaKeyStrict 严格按照键字段类型格式化Lua键
func formatLuaKeyStrict(key string, keyFieldType string) string {
	switch keyFieldType {
	case "int", "integer", "float", "double", "number":
		// 对于数字类型，确保使用数字键格式
		if _, err := strconv.Atoi(key); err == nil {
			return fmt.Sprintf("[%s]", key)
		}
		// 如果无法解析为数字，使用字符串键
		return fmt.Sprintf(`["%s"]`, key)
	case "string":
		// 对于字符串类型，始终使用字符串键
		return fmt.Sprintf(`["%s"]`, key)
	default:
		// 其他类型尝试推断
		if _, err := strconv.Atoi(key); err == nil {
			return fmt.Sprintf("[%s]", key)
		}
		return fmt.Sprintf(`["%s"]`, key)
	}
}

// getFieldOrder 获取字段的顺序（保持一致性）
func getFieldOrder(row types.DataRow) []string {
	// 优先保持一些常见字段的顺序
	preferredOrder := []string{"Id", "ItemId", "name", "type"}
	
	// 收集所有字段
	allFields := make([]string, 0, len(row))
	for k := range row {
		allFields = append(allFields, k)
	}
	
	// 创建结果切片
	result := make([]string, 0, len(row))
	
	// 首先添加优先字段（如果存在）
	for _, field := range preferredOrder {
		if _, exists := row[field]; exists {
			result = append(result, field)
		}
	}
	
	// 然后添加其他字段
	for _, field := range allFields {
		found := false
		for _, existing := range result {
			if existing == field {
				found = true
				break
			}
		}
		if !found {
			result = append(result, field)
		}
	}
	
	return result
}

// formatLuaValue 格式化Lua值（带键名）
func formatLuaValue(key string, value interface{}) string {
	switch v := value.(type) {
	case string:
		return fmt.Sprintf(`%s = "%s"`, key, v)
	case int, float64, bool:
		return fmt.Sprintf(`%s = %v`, key, v)
	case []interface{}:
		return formatLuaArray(key, v)
	case map[string]interface{}:
		return formatLuaMapWithKey(key, v)
	default:
		return fmt.Sprintf(`%s = "%v"`, key, v)
	}
}

// formatLuaValueSimple 格式化Lua值（不带键名，用于顶层字段）
func formatLuaValueSimple(value interface{}) string {
	switch v := value.(type) {
	case string:
		return fmt.Sprintf(`"%s"`, v)
	case int, float64, bool:
		return fmt.Sprintf(`%v`, v)
	case []interface{}:
		return formatLuaArraySimple(v)
	case map[string]interface{}:
		return formatLuaMap(v)
	default:
		return fmt.Sprintf(`"%v"`, v)
	}
}

// formatLuaArray 格式化Lua数组（带键名）
func formatLuaArray(key string, array []interface{}) string {
	var builder strings.Builder
	builder.WriteString(fmt.Sprintf(`%s = {`, key))
	
	for j, item := range array {
		if j > 0 {
			builder.WriteString(", ")
		}
		builder.WriteString(formatLuaValueSimple(item))
	}
	
	builder.WriteString("}")
	return builder.String()
}

// formatLuaArraySimple 格式化Lua数组（不带键名）
func formatLuaArraySimple(array []interface{}) string {
	var builder strings.Builder
	builder.WriteString("{")
	
	for j, item := range array {
		if j > 0 {
			builder.WriteString(", ")
		}
		builder.WriteString(formatLuaValueSimple(item))
	}
	
	builder.WriteString("}")
	return builder.String()
}

// formatLuaMap 格式化Lua表
func formatLuaMap(m map[string]interface{}) string {
	var builder strings.Builder
	builder.WriteString("{\n")
	
	first := true
	for key, value := range m {
		if !first {
			builder.WriteString(",\n")
		}
		builder.WriteString(fmt.Sprintf("        %s = ", formatLuaKeyStrict(key, "string")))
		builder.WriteString(formatLuaValueSimple(value))
		first = false
	}
	
	builder.WriteString("\n    }")
	return builder.String()
}

// formatLuaMapWithKey 格式化带键名的Lua表
func formatLuaMapWithKey(key string, m map[string]interface{}) string {
	var builder strings.Builder
	builder.WriteString(fmt.Sprintf(`%s = {`, key))
	
	first := true
	for k, v := range m {
		if !first {
			builder.WriteString(", ")
		}
		builder.WriteString(fmt.Sprintf(`%s = `, formatLuaKeyStrict(k, "string")))
		builder.WriteString(formatLuaValueSimple(v))
		first = false
	}
	
	builder.WriteString("}")
	return builder.String()
}